<template>
  <!-- 人员信息 -->
  <section class="staff-content">
    <section class="staff-table">
      <header>
        <h3>供应商人员信息</h3>
      </header>
      <AdvancedTable
        ref="xTable"
        :autoResize="true"
        :edit-config="editConfig"
        :edit-rules="editRules[0]"
        :toolbarConfig="toolbarConfig"
        :dataSource="supplierStaffTableList"
        :columns="supplierStaffTableColumns">
        <template #toolbar_buttons>
          <el-button
            v-if="showExportBtn && !readonly"
            :loading="exporting"
            icon="el-icon-download"
            type="primary"
            @click="handleExportSupplierStaffFile">导出</el-button>
          <el-button v-if="!readonly" type="primary"
          @click="handleInsertSupplierStaff">添加行</el-button>
        </template>

        <template #name_edit="{ row }">
          <vxe-input v-model.trim="row.personName" class="name-input" placeholder="请输入姓名" @change="handleInputChange"></vxe-input>
        </template>
        <template #sex_edit="{ row, _rowIndex }">
          <vxe-select v-model="row.personSex" @change="({value})=>{handlePersonSexChange(value, _rowIndex)}" placeholder="请选择性别" transfer>
            <vxe-option v-for="(item,key) in sexList" :key="key" :value="item.value" :label="item.label" :disabled="item.disabled"></vxe-option>
          </vxe-select>
        </template>
        <template #sex_default="{ row }">
          <span v-if="row.personSex">{{GENDER_MAP_OBJECT[row.personSex]}}</span>
          <span v-else class="vxe-cell--placeholder">请点击选择...</span>
        </template>
        <template #id_edit="{ row }">
          <vxe-input v-model.trim="row.idCard" class="id-input" maxlength="18" placeholder="请输入身份证号" @change="handleInputChange"></vxe-input>
        </template>
        <template #post_edit="{ row }">
          <vxe-input v-model.trim="row.personPost" class="role-input" placeholder="请输入职务" @change="handleInputChange"></vxe-input>
        </template>
        <template #role_edit="{ row, _rowIndex }">
          <vxe-select v-model="row.personRole" @change="({value})=>{handlePersonRoleChange(value, _rowIndex)}" placeholder="请选择角色" transfer clearable>
            <vxe-option v-for="(item,key) in jobList" :key="key" :value="item.value" :label="item.label" :disabled="item.disabled"></vxe-option>
          </vxe-select>
        </template>
        <template #role_default="{ row }">
          <span v-if="row.personRole">{{JOB_TITLE_MAP_OBJECT[row.personRole]}}</span>
          <span v-else class="vxe-cell--placeholder">请点击选择...</span>
        </template>
        <template #superior_edit="{ row, _rowIndex }">
          <vxe-pulldown ref="xDown" transfer>
            <template #default>
              <vxe-input v-model.trim="row.directSuperior" placeholder="请输入直属上级"  @keyup="keyupEvent(_rowIndex)"></vxe-input>
            </template>
            <template #dropdown>
              <vxe-list height="200" class="superior-dropdown" :data="superiorList" auto-resize>
                <template #default="{ items }">
                  <div class="list-item" v-for="(item,key) in items" :key="key" @click="selectEvent(item, _rowIndex)">
                    <span>{{ item.label }}</span>
                  </div>
                </template>
              </vxe-list>
            </template>
          </vxe-pulldown>
        </template>
        <template #scope_edit="{ row }">
          <vxe-input v-model.trim="row.managementScope" class="scope-input" placeholder="请输入管理范围" @change="handleInputChange"></vxe-input>
        </template>
        <template #service_area_edit="{ row, _rowIndex }">
          <!-- <vxe-select
            v-model="row.serviceAreaIds"
            placeholder="请选择服务区域"
            @change="({value})=>{handleServiceAreaChange(value, _rowIndex)}"
            transfer
            multiple>
            <vxe-option label='全选' value='全选' @click.native='handleSelectAll(_rowIndex)'></vxe-option>
            <vxe-option v-for="(item,key) in addressList" :key="key" :value="item.addressId" :label="item.addressName" ></vxe-option>
          </vxe-select> -->
          <el-select
            v-model="row.serviceAreaIds"
            placeholder="请选择服务区域"
            @change="(value)=>{handleSelectChange(value, _rowIndex)}"
            transfer
            collapse-tags
            multiple>
            <el-option label='全选' value='全选' @click.native='handleSelectAll(_rowIndex)'></el-option>
            <el-option v-for="(item,key) in addressList" :key="key" :value="item.addressId" :label="item.addressName" ></el-option>
          </el-select>
        </template>
        <template #service_area_default="{ row }">
          <span v-if="row.serviceArea">{{row.serviceArea}}</span>
          <span v-else class="vxe-cell--placeholder">请点击选择...</span>
        </template>
        <template #phone_edit="{ row }">
          <vxe-input v-model.trim="row.contactPhone" class="phone-input" placeholder="请输入联系电话" @change="handleInputChange"></vxe-input>
        </template>
        <template #wxqq_edit="{ row }">
          <vxe-input v-model.trim="row.wxQq" class="wxqq-input" placeholder="请输入微信/QQ" @change="handleInputChange"></vxe-input>
        </template>
        <template #email_edit="{ row }">
          <vxe-input v-model.trim="row.email" class="email-input" placeholder="请输入E-mail" @change="handleInputChange"></vxe-input>
        </template>
        <template #actions="{ row, _rowIndex }">
          <vxe-button v-if="_rowIndex" type="text" status="primary" @click="removeSupplierRow(row, _rowIndex)">删除行</vxe-button>
        </template>
      </AdvancedTable>
      <!-- <pre>{{supplierStaffTableList}}</pre> -->
    </section>
    <section v-if="dataSource.length === 2" class="staff-table">
      <header>
        <h3>我司人员信息</h3>
      </header>
      <AdvancedTable
        ref="yTable"
        :autoResize="true"
        :edit-config="editConfig"
        :edit-rules="editRules[1]"
        :toolbarConfig="toolbarConfig"
        :dataSource="staffTableList"
        :columns="staffTableColumns">
        <template #toolbar_buttons>
          <el-button
            v-if="showExportBtn && !readonly"
            :loading="exporting"
            icon="el-icon-download"
            type="primary"
            @click="handleExportStaffFile">导出</el-button>
          <el-button v-if="!readonly" type="primary"
           @click="handleInsertStaff">添加行</el-button>
        </template>

        <template #name="{ row, _rowIndex }">
          {{row.personName}}
          <el-button v-if="!readonly" type="primary" @click="handleShowUserSelectDialog(_rowIndex)">
            添加人员
          </el-button>
        </template>
        <!-- <template #sex_edit="{ row }">
          <vxe-select v-model="row.sex" transfer>
            <vxe-option v-for="(item,key) in sexList" :key="key" :value="item.value" :label="item.label" :disabled="item.disabled"></vxe-option>
          </vxe-select>
        </template> -->
        <template #role_edit="{ row }">
          <vxe-select v-model="row.personRole" @change="handleStaffRoleChange" placeholder="请选择角色" transfer clearable>
            <vxe-option v-for="(item,key) in staffJobList" :key="key" :value="item.value" :label="item.label" :disabled="item.disabled"></vxe-option>
          </vxe-select>
        </template>
        <template #role_default="{ row }">
          <span v-if="row.personRole">{{JOB_TITLE_MAP_OBJECT[row.personRole]}}</span>
          <span v-else class="vxe-cell--placeholder">请点击选择...</span>
        </template>
        <template #actions="{ row, _rowIndex }">
          <vxe-button v-if="_rowIndex" type="text" status="primary" @click="removeStaffRow(row, _rowIndex)">删除行</vxe-button>
        </template>
      </AdvancedTable>
      <!-- <pre>{{staffTableList}}</pre> -->
      <UserSelectDialog
        :dialogVisible.sync="dialogVisible"
        @handle-select="handleGetUser"
      />
    </section>
  </section>
</template>

<script>
import { getBtnsId } from '@/libs/btnsPermission';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import AdvancedTable from '@/components/supplier/AdvancedTable'; // 表格组件
import UserSelectDialog from '@/pages/supplier/components/userSelectDialog'; // 用户选择组件
import { getSupplierDirectSuperior, getAddressList, queryHrUserService } from '@/api/supplier/components'
import {
  GENDER_SELECT_LIST,
  JOB_TITLE_SELECT_LIST
} from '@/pages/supplier/constants/common'
import { supplierStaffInformation } from '@/pages/supplier/constants'
import { list2Obj } from '@/pages/supplier/utils';
const {
  getSupplierStaffTableColumns,
  getInitialSupplierFieldsValue,
  getStaffTableColumns,
  INITIAL_STAFF_FIELDS_VALUE,
} = supplierStaffInformation

export default {
  components: {
    AdvancedTable,
    UserSelectDialog,
  },
  props: {
    showExportBtn: { type: Boolean, default: false }, // 是否显示导出按钮
    readonly: { type: Boolean, default: false }, // 是否只读
    isQualified: { type: Boolean, default: false }, // 是否合格供应商
    isClues: { type: Boolean, default: false }, // 是否线索供应商
    dataSource: { type: Array, default () { return []; } }, // 数据源
    rules: { // 数据验证
      type: Array,
      default () {
        return [{
          personName: [{ required: true, message: '请输入供应商人员姓名' }],
          personSex: [{ required: !this.isClues, message: '请选择供应商人员性别' }, {
            validator: ({ cellValue }) => {
              if (!cellValue && !this.isClues) {
                return new Error('请选择供应商人员性别!')
              }
            }
          }],
          idCard: [{// required: this.isQualified, message: '请输入供应商人员身份证号' }, {
            validator: ({ cellValue }) => {
              if (cellValue) {
                const _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
                // 校验身份证：
                if (!_IDRe18.test(cellValue) && !_IDre15.test(cellValue)) {
                  return new Error('请输入合法身份证号!')
                }
              }
            }
          }],
          personPost: [{ required: !this.isClues, message: '请输入供应商人员职务' }],
          personRole: [{ required: true, message: '请选择供应商人员角色' }, {
            validator: ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
              const { supplierStaffTableList: list } = this
              if (this.isClues) {
                if (list.length < 1) {
                  return new Error('请至少添加 1 位供应商人员!')
                }
                if (!list.some(i => i.personRole === 2)) {
                  return new Error('请选择 1 位主要业务联系人!')
                }
              } else if (list.length < 2) {
                return new Error('请至少添加 2 位供应商人员!')
              } else {
                if (!list.some(i => i.personRole === 2)) {
                  return new Error('请选择 1 位主要业务联系人!')
                }
                if (!list.some(i => i.personRole === 6)) {
                  return new Error('请选择 1 位业务决策人!')
                }
              }
            }
          }],
          contactPhone: [{ required: true, message: '请输入供应商人员联系电话' }, {
            validator: ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
              if (!/^\d{3}-\d{8}$|\d{4}-\d{8}$|^1[3456789]\d{9}$/.test(cellValue)) {
                return new Error('请输入合法的联系电话!')
              }
            }
          }],
          email: [{
            validator: ({ cellValue }) => {
              if (cellValue) {
                const _emialRule = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                if (!_emialRule.test(cellValue)) {
                  return new Error('请输入合法邮箱地址!')
                }
              }
            }
          }],
        },
        {
          personName: [{ required: true, message: '请添加我司人员' }],
          // sex: [{ required: true, message: '请选择我司人员性别' }],
          personRole: [{ required: true, message: '请选择我司人员角色' }],
        }];
      }
    }
  },
  computed: {
    toolbarConfig () {
      if (this.readonly) {
        return {}
      }
      return {
        slots: {
        // 自定义工具栏模板
          buttons: 'toolbar_buttons',
        }
      }
    },
    editConfig () {
      if (this.readonly) {
        return {}
      }
      return { trigger: 'click', mode: 'row' }
    },
    editRules () {
      if (this.readonly) {
        return {}
      }
      return this.rules
    },
  },
  data () {
    const { dataSource, isQualified, readonly } = this
    const [ supplierPersonBillList = [], supplierPersonOurBillList = [] ] = dataSource
    const supplierStaffTableColumns = getSupplierStaffTableColumns(isQualified, readonly)
    const staffTableColumns = getStaffTableColumns(readonly)

    const GENDER_MAP_OBJECT = list2Obj(GENDER_SELECT_LIST)
    const JOB_TITLE_MAP_OBJECT = list2Obj(JOB_TITLE_SELECT_LIST)
    return {
      GENDER_MAP_OBJECT,
      JOB_TITLE_MAP_OBJECT,
      valid: true,
      supplierStaffTableColumns,
      staffTableColumns,
      exporting: false,
      dialogVisible: false,
      index: 0,
      supplierStaffTableList: [...supplierPersonBillList],
      staffTableList: [...supplierPersonOurBillList],
      sexList: GENDER_SELECT_LIST,
      jobList: _.cloneDeep(JOB_TITLE_SELECT_LIST),
      staffJobList: _.cloneDeep(JOB_TITLE_SELECT_LIST.filter(i => i.value !== 1)),
      supplierStaffData: _.cloneDeep(getInitialSupplierFieldsValue(this.isQualified)),
      staffTData: _.cloneDeep(INITIAL_STAFF_FIELDS_VALUE),
      superiorList: [],
      addressList: [],
    };
  },
  watch: {
    supplierStaffTableList: {
      handler (newVal, oldVal) {
        if (newVal) {
          this.$emit('change', { value: newVal, prop: 'supplierPersonBillList' })
        }
      },
      immediate: true,
      deep: true
    },
    staffTableList: {
      handler (newVal, oldVal) {
        if (newVal) {
          this.$emit('change', { value: newVal, prop: 'supplierPersonOurBillList' })
        }
      },
      immediate: true,
      deep: true
    },
    dataSource: {
      handler (newVal, oldVal) {
        const [ supplierPersonBillList = [], supplierPersonOurBillList = [] ] = newVal
        if (!oldVal && newVal) {
          if (supplierPersonBillList && supplierPersonBillList.length) {
            this.supplierStaffTableList = supplierPersonBillList.map(i => {
              i.idCard = i.idCard.replace('无', '').trim()
              i.contactPhone = i.contactPhone.replace('无', '').trim()
              return i
            })
          } else {
            const item1 = _.cloneDeep(this.supplierStaffData)
            const item2 = _.cloneDeep(this.supplierStaffData)
            item1.personRole = 2
            item2.personRole = 6
            if (this.isClues) {
              this.supplierStaffTableList = [item1]
            } else {
              this.supplierStaffTableList = [item1, item2]
            }
          }
          if (supplierPersonOurBillList && supplierPersonOurBillList.length) {
            this.staffTableList = supplierPersonOurBillList
          } else {
            // this.staffTableList = [_.cloneDeep(INITIAL_STAFF_FIELDS_VALUE)]
            this.getDefaultHrUserData()
          }
        }
      },
      immediate: true,
      deep: true
    },
  },
  created () {
    const { supplierStaffTableList, isQualified, staffTableList, supplierStaffData } = this
    if (!supplierStaffTableList.length) {
      supplierStaffTableList.push(_.cloneDeep(supplierStaffData))
    }
    if (!staffTableList.length) {
      staffTableList.push(_.cloneDeep(INITIAL_STAFF_FIELDS_VALUE))
    }
    if (isQualified) {
      this.getAddressList()
    }
  },
  methods: {
    async handleInsertSupplierStaff () {
      let cloneObj = _.cloneDeep(this.supplierStaffData)
      const [first] = this.supplierStaffTableList;
      if (first && first.supplierId) {
        const { supplierId, supplierCode } = first
        cloneObj = Object.assign(cloneObj, { supplierId, supplierCode })
      }
      const $table = this.$refs.xTable.$refs.grid
      await $table.insertAt(cloneObj, -1)
      this.supplierStaffTableList.push(cloneObj)
      this.handleDisableJobListItem()
    },
    async handleInsertStaff () {
      let cloneObj = _.cloneDeep(INITIAL_STAFF_FIELDS_VALUE)
      const [first] = this.staffTableList;
      if (first && first.supplierId) {
        const { supplierId, supplierCode } = first
        cloneObj = Object.assign(cloneObj, { supplierId, supplierCode })
      }
      const $table = this.$refs.yTable.$refs.grid
      await $table.insertAt(cloneObj, -1)
      this.staffTableList.push(cloneObj)
    },
    // 删除行
    removeSupplierRow (row, index) {
      this.$refs.xTable.$refs.grid.remove(row)
      this.supplierStaffTableList.splice(index, 1)
      this.handleDisableJobListItem()
    },
    // 删除行
    removeStaffRow (row, index) {
      this.$refs.yTable.$refs.grid.remove(row)
      this.staffTableList.splice(index, 1)
    },
    handleInputChange () {
      this.$refs.xTable.$refs.grid.clearValidate()
    },
    // 供应商人员 - 性别选择
    handlePersonSexChange (value, index) {
      // console.log('性别选择 :>> ', value);
      this.$refs.xTable.$refs.grid.clearValidate()
    },
    // 供应商人员 - 角色选择
    handlePersonRoleChange (value, index) {
      // console.log('角色选择 :>> ', value);
      this.$refs.xTable.$refs.grid.clearValidate()
      this.handleDisableJobListItem()
    },
    // 供应商人员 - 服务区域选择
    handleServiceAreaChange (ids, index) {
      // console.log('服务区域选择 :>> ', ids);
      // console.log('index :>> ', index);
      this.$refs.xTable.$refs.grid.clearValidate()
      this.supplierStaffTableList[index].serviceAreaIds = ids
      this.supplierStaffTableList[index].serviceAreaList = ids.map(id => {
        const { addressId, addressName } = this.addressList.find(i => i.addressId === id) || {}
        return {
          itemId: addressId,
          itemName: addressName
        }
      })
      this.supplierStaffTableList[index].serviceArea = this.supplierStaffTableList[index].serviceAreaList.map(i => i.itemName).join()
    },
    // 服务区域全选
    handleSelectAll (index) {
      if (this.supplierStaffTableList[index].serviceAreaIds.length < this.addressList.length) {
        this.handleServiceAreaChange(this.addressList.map(item => item.addressId), index)
      } else {
        this.handleServiceAreaChange([], index)
      }
    },
    // 服务区域
    handleSelectChange (val, index) {
      if (!val.includes('全选') && val.length === this.addressList.length) {
        // this.supplierStaffTableList[index].serviceAreaIds.unshift('全选')
      } else if (val.includes('全选') && (val.length - 1) < this.addressList.length) {
        this.handleServiceAreaChange(this.supplierStaffTableList[index].serviceAreaIds.filter(item => item !== '全选'), index)
      } else {
        this.handleServiceAreaChange(val, index)
      }
    },
    // 我司人员 - 角色选择
    handleStaffRoleChange ({ value }) {
      this.$refs.yTable.$refs.grid.clearValidate()
      // this.staffJobList[1].disabled = this.staffTableList.some(i => i.personRole === 2)
    },
    handleShowUserSelectDialog (index) {
      this.index = index;
      this.dialogVisible = true
    },
    keyupEvent (index) {
      const { directSuperior } = this.supplierStaffTableList[index]
      this.queryDirectSuperior(directSuperior)
    },
    selectEvent (item, index) {
      this.supplierStaffTableList[index].directSuperior = item.label
      this.$refs.xDown.hidePanel()
    },
    // 获取直属上级
    async queryDirectSuperior (queryString, cb) {
      if (!queryString) {
        return
      }
      const { result: { records = [] } } = await getSupplierDirectSuperior({ personName: queryString, current: 1, size: 1000 })
      if (records && records.length) {
        this.superiorList = records.map(i => {
          return { label: i.personName }
        })
        this.$refs.xDown.showPanel()
      } else {
        this.superiorList = []
        this.$refs.xDown.hidePanel()
      }
    },
    getAddressList () {
      getAddressList({}).then(({ result = [] }) => {
        this.addressList = result
      })
    },
    handleExportSupplierStaffFile () {

    },
    handleExportStaffFile () {

    },
    // 获取已选人员
    handleGetUser (row, personRole) {
      const { hrArea, hrJobName, mobile, userName, jobNumber, sex } = row;
      const obj = {
        sex,
        personName: userName,
        jobNo: jobNumber,
        personPost: hrJobName,
        contactPhone: mobile,
        belongArea: hrArea,
        personRole: personRole || '',
      }
      this.staffTableList[this.index] = Object.assign(this.staffTableList[this.index], obj)
      this.$refs.yTable.$refs.grid.reloadData(this.staffTableList)
    },
    async validate () {
      let errMap = false
      errMap = await this.$refs.xTable.$refs.grid.validate(true)
      if (errMap) {
        this.valid = false
        return errMap
      } else {
        this.valid = true
      }
    },
    async getValidate () {
      let errMap = false
      errMap = await this.$refs.xTable.$refs.grid.validate(true)
      // console.log('xTable errMap -:>> ', errMap)
      if (errMap) {
        return errMap
      } else {
        if (this.dataSource.length === 2) {
          errMap = await this.$refs.yTable.$refs.grid.validate(true)
          // console.log('yTable errMap -:>> ', errMap);
          return errMap
        } else {
          return errMap
        }
      }
      // return this.$refs.xTable.$refs.grid.validate(true)
    },
    getData () {
      return this.dataSource
    },
    // 供应商人员信息，职务增加逻辑【主要业务联系人】仅可存一个
    handleDisableJobListItem () {
      this.jobList[1].disabled = this.supplierStaffTableList.some(i => i.personRole === 2)
    },
    // 获取 当前登陆人信息
    getDefaultHrUserData () {
      const currentUserInfo = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {}
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      queryHrUserService({ jobNumber: currentUserInfo?.jobNumber, pageNum: 1, pageSize: 10 }).then(res => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          if (result.list && result.list.length) {
            // 主要业务联系人 personRole: 2
            this.handleGetUser(result.list[0], 2)
          }
        }
      }).catch(() => {});
    },
  },
}
</script>

<style lang="less" scoped>
.staff-content {
  header {
    text-align: left;
    margin-bottom: 0;
  }
  .staff-table + .staff-table {
    margin-top: 20px;
  }
}
.superior-dropdown{
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #dadce0;
  box-shadow: 0 0 6px 2px rgba(0,0,0,.1);
  background-color: #fff;
  .list-item {
    padding: 4px;
    &:hover {
      cursor: pointer;
      background-color: #f9f9f9;
    }
  }
}
</style>
